package com.pingan.abc.onenews.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.TextHttpResponseHandler;
import com.orhanobut.logger.Logger;
import com.pingan.abc.onenews.MyWebViewActivity;
import com.pingan.abc.onenews.R;
import com.pingan.abc.onenews.bean.BannerBean;
import com.pingan.abc.onenews.bean.NewsBean;
import com.pingan.abc.onenews.tools.GlideImageLoader;
import com.pingan.abc.onenews.tools.MyHttpClient;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public class MainFragment extends Fragment {
    private String baseUrl = "https://www.wanandroid.com/";
    private ListView listView;
    private RecyclerView recyclerView;
    private NewsAdapter newsAdapter;
    private ProgressBar progressBar;
    private Banner banner;
    private ArrayList<NewsBean> adapterDatas = new ArrayList<>();
    private ArrayList<BannerBean> bannerDatas = new ArrayList<>();
    private List<String> imgUrls=new ArrayList<>();

    public MainFragment() {
        // Required empty public constructor
    }

    public static MainFragment newInstance() {
        MainFragment fragment = new MainFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main_layout, container, false);
        listView = view.findViewById(R.id.listview);
        recyclerView = view.findViewById(R.id.recyclerView);
        progressBar = view.findViewById(R.id.progressBar);
        banner = view.findViewById(R.id.banner);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
        //设置图片加载器
//        banner.setImageLoader(new GlideImageLoader());
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
              BannerBean data=bannerDatas.get(position);
                Toast.makeText(getContext(), ""+data.getImagePath(), Toast.LENGTH_SHORT).show();
                startActivity(new Intent(getContext(),MyWebViewActivity.class).putExtra("url",data.getUrl()));
            }
        });
        banner.setImageLoader(new GlideImageLoader());

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
//        recyclerView.setItemAnimator(new DefaultItemAnimator());
//        recyclerView.adapterDatas
//        recyclerView.addItemDecoration(new De);
        newsAdapter = new NewsAdapter();
        recyclerView.setAdapter(newsAdapter);
        getData(0);
        loadBanner();
        return view;

    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.stopAutoPlay();
    }

    private void loadBanner() {
        MyHttpClient.getInstance().get(baseUrl + "banner/json", new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Logger.json(response.toString());
                if (null == response)
                    return;
                ArrayList<String> titles=new ArrayList<>();
                if ("0".equals(response.optString("errorCode"))) {
                    JSONArray array = response.optJSONArray("data");
                    if (array != null) {
                        for (int i = 0; i < array.length(); i++) {
                            try {
                                JSONObject obj=array.getJSONObject(i);
                                BannerBean b = new BannerBean();
                                b.setImagePath(obj.optString("imagePath"));
                                b.setUrl(obj.optString("url"));
                                b.setDesc(obj.optString("desc"));
                                b.setTitle(obj.optString("title"));
                                bannerDatas.add(b);
                                imgUrls.add(b.getImagePath());
                                titles.add(b.getTitle());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                        banner.setImages(imgUrls);

                        banner.setBannerTitles(titles);
                        banner.start();
                        Logger.d("yes...");
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });
    }

    private void getData(int pageNum) {
        MyHttpClient.getInstance().get(baseUrl + "article/list/" + pageNum + "/json", new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Logger.e(responseString);
                throwable.printStackTrace();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                progressBar.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
//                Logger.json(responseString);
                try {
                    JSONObject obj = new JSONObject(responseString);
                    int status = obj.optInt("errorCode", -1);
                    if (status != 0) {
                        Logger.e(statusCode + "");
                        Toast.makeText(getContext(), "response error", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    JSONArray array = obj.optJSONObject("data").optJSONArray("datas");
                    if (null == array)
                        return;
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject data = array.getJSONObject(i);
                        NewsBean b = new NewsBean();
                        b.setDesc(data.optString("desc"));
                        b.setEnvelopePic(data.optString("envelopePic"));
                        b.setNiceDate(data.optString("niceDate"));
                        b.setLink(data.optString("link"));
                        b.setTitle(data.optString("title"));
                        b.setAuthor(data.optString("author"));
                        adapterDatas.add(b);
                    }
                    newsAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public class NewsAdapter extends RecyclerView.Adapter<MyViewHolder> {


        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.news_item_layout2, null);
            MyViewHolder myViewHolder = new MyViewHolder(view);
            return myViewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            final NewsBean data = adapterDatas.get(position);
            if (data != null) {
                holder.tv_title.setText(data.getTitle() + "");
                holder.tv_source.setText(data.getAuthor() + "");
                holder.tv_date.setText(data.getNiceDate() + "");
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        Toast.makeText(getContext(), ""+data.getLink(), Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(getContext(), MyWebViewActivity.class).putExtra("url", data.getLink()));
                    }
                });
                if (!TextUtils.isEmpty(data.getEnvelopePic()))
                    Glide.with(getContext()).load(data.getEnvelopePic()).into(holder.img);

            }
        }

        @Override
        public int getItemCount() {
            return adapterDatas.size();
        }
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView tv_title, tv_source, tv_date;
        ImageView img;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_title = itemView.findViewById(R.id.tv_title);
            tv_source = itemView.findViewById(R.id.tv_source);
            tv_date = itemView.findViewById(R.id.tv_date);
            img = itemView.findViewById(R.id.iv_img);
        }
    }

}
